package de.uni_potsdam.hpi.bpt.ai.collection.impl;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.json.JSONException;

import de.uni_potsdam.hpi.bpt.ai.collection.Revision;
import de.uni_potsdam.hpi.bpt.ai.diagram.Diagram;
import de.uni_potsdam.hpi.bpt.ai.diagram.DiagramBuilder;

import org.springframework.util.FileCopyUtils;

public class RevisionImpl implements Revision{

	private Integer number;
	private File svg;

	private File json;

	public RevisionImpl() {
	}

	@Override
	public int compareTo(Revision o) {
		if(getNumber()==null && o.getNumber()==null){
			return 0;
		}else if(getNumber()==null && o.getNumber()!=null){
			return -1;
		}else if(getNumber()!=null && o.getNumber()==null){
			return 1;
		}else{
			return getNumber().compareTo(o.getNumber());
		}
	}

	/* (non-Javadoc)
	 * @see org.oryxproject.bpm_ai.Revision#getDiagram()
	 */
	@Override
	public Diagram getDiagram() throws JSONException, UnsupportedEncodingException, FileNotFoundException, IOException {
		return DiagramBuilder.parseJson(readFileToString(json));
	}
	/* (non-Javadoc)
	 * @see org.oryxproject.bpm_ai.Revision#getJson()
	 */
	@Override
	public File getJson() {
		return json;
	}

	/* (non-Javadoc)
	 * @see org.oryxproject.bpm_ai.Revision#getNumber()
	 */
	@Override
	public Integer getNumber() {
		return number;
	}
	/* (non-Javadoc)
	 * @see org.oryxproject.bpm_ai.Revision#getSvg()
	 */
	@Override
	public File getSvg() {
		return svg;
	}

	protected String readFileToString(File file) throws UnsupportedEncodingException, FileNotFoundException, IOException {
			return FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(file), "UTF-8"));
	}
	public void setJson(File json) {
		this.json = json;
	}

	public void setNumber(Integer number) {
		this.number = number;
	}




	public void setSvg(File svg) {
		this.svg = svg;
	}
	
}
